
import { getEcCom } from '../convert';
//字段变更类型 
export const TYPE_MAIN_INIT = "1";        //主表字段初始值加载
export const TYPE_DETAIL_ADDROW = "2";    //添加/生成明细行的默认值
export const TYPE_FIELD_CHANGE = "3";     //手动变更字段
export const TYPE_LINKAGE_SYNC = "4";     //同步联动修改
export const TYPE_LINKAGE_ASYNC = "5";    //异步联动修改
export const TYPE_WFFORM_API = "6";       //通过接口WfForm修改(包括公式)
export const CHANGE_FIELD_VALUE = "c_value";    //改变字段值
export const CHANGE_FIELD_VARS = "c_vars";      //改变字段属性

let modifyStep = {};
let stepIndex = 0;

/**
 *
 */
export const setDocParam = (odocInfo,maindata) =>{

    var docInfonew = odocInfo;
    var documentFieldId = docInfonew.docParam.documentTitleField;
    if(documentFieldId === -3 || documentFieldId === 0)documentFieldId = -1;
    var formFieldList = docInfonew.formFieldList;
    var fieldTotalList = new Array();
    //编辑模板字段
    for (var i = 0; formFieldList && i < formFieldList.length; i++) {
        var fieldid = formFieldList[i];
        if (fieldTotalList.indexOf(fieldid) >= 0) continue;
        fieldTotalList.push(fieldid);
    }
    //选择框目录字段
    if (fieldTotalList.indexOf(docInfonew.docParam.secFieldid) == -1) fieldTotalList.push(docInfonew.docParam.secFieldid);


    //文档标题
    if (fieldTotalList.indexOf(docInfonew.docParam.secFieldid) == -1) {
        fieldTotalList.push(docInfonew.docParam.secFieldid);
    }

    //选择框目录字段
    if (fieldTotalList.indexOf(docInfonew.docParam.documentTitleField) == -1) fieldTotalList.push(docInfonew.docParam.documentTitleField);

    if (window.console) console.log("fieldTotalList", fieldTotalList);
    var fieldTotalObj = getFromFieldValue(fieldTotalList,maindata);
    if (window.console) console.log("fieldTotalObj", fieldTotalObj);
    // for (var fieldInfo in fieldTotalObj) {//不使用过滤
    //     docInfonew.docParam[fieldInfo] = fieldTotalObj[fieldInfo];
    // }
    //保留需要带入URL参数的内容
    docInfonew.nowDocParam = new Object();
    docInfonew.nowDocParam = cloneObject(docInfonew.docParam);
    for (var fieldInfo in fieldTotalObj) {//不使用过滤
        docInfonew.nowDocParam[fieldInfo] = fieldTotalObj[fieldInfo];
    }


    //模板书签对应字段
    var formFieldList = docInfonew.formFieldList;
    var formFieldObj = getFromFieldValue(formFieldList?formFieldList:[],maindata);
    //模板书签对应，不需要带入URL参数中，但是需要记录变化
    for (var fieldInfo in formFieldObj) {
        docInfonew.nowDocParam[fieldInfo] = formFieldObj[fieldInfo];
    }

    //是否需要重新加载url
    docInfonew.needReload = false;
    if (!ObjectEquals(docInfonew.nowDocParam, docInfonew.lasttimeDocParam)) {

        docInfonew.needReload = true;

        docInfonew.lasttimeDocParam = new Object();
        docInfonew.lasttimeDocParam = cloneObject(docInfonew.nowDocParam);
    } else {
        docInfonew.needReload = false;
    }
    if (window.console) console.log("docInfonew---new", docInfonew);

    WfForm.changeOdocConfig(docInfonew);
    if (docInfonew.needReload) {
        var url = docInfonew.docUrl + "?";
        var count = 0;
        var router = docInfonew.docParam.router;
        if (docInfonew.docParam.isEdit == 1) {
            router = "#/main/document/edit";
        } else {
            router = "#/main/document/detail";
        }
        for (var key in docInfonew.docParam) {
            if (key == "router") continue;
            if(!(docInfonew.docParam[key])) continue;
            if (count > 0) url += "&";
            url += key + "=" + encodeURIComponent(docInfonew.docParam[key]);
            count++;
        }
        var dataJson = cloneObject(docInfonew.nowDocParam);
        dataJson.action = 'setUrlParams';
        const { WeaTools } = getEcCom();
        WeaTools.callApi('/api/odoc/odocWorkflow/setUrlParams?date=' + new Date(), 'POST', {...dataJson}).then(result =>{
            if(result.success){
                url += "&uuid=" + result.uuid;
            }
        });
        //TODO
        // jQuery.ajax({
        //     type: "POST",
        //     url: "/odoc/docs/odocCommonAjax.jsp?date="+new Date(),
        //     data: dataJson,
        //     async: false,
        //     cache: false,
        //     dataType: 'json',
        //     success: function (returndata) {
        //         retFlag = returndata.success;
        //         url += "&uuid=" + returndata.uuid;
        //     }
        // });
        url += router;
        try {
            document.getElementsByClassName("req-workflow-odoc")[0].contentWindow.onbeforeunload = null;
        } catch (e) {
        }
        //
        // document.getElementsByClassName("wf-req-odoc").css("margin-top", "10px");
        // document.getElementsByClassName("wf-req-odoc").css("margin-bottom", "10px");
        // document.getElementsByClassName("wf-req-odoc").height(document.getElementsByClassName("wea-new-top-req-content").height() - 20);
        // document.getElementsByClassName("req-workflow-odoc").height(document.getElementsByClassName("wf-req-odoc").height());
        // document.getElementsByClassName("req-workflow-odoc").attr("src", url);
        docInfonew.iframeUrl = url;
        odocInfo = docInfonew;
    }
}

export const getFromFieldValue = (fieldList,maindata) => {
    var retObj = new Object();
    for (var i = 0; i < fieldList.length; i++) {
        var fieldid = fieldList[i];
        if (fieldid == "-3") {
            var fieldvalue = WfForm.getFieldValue("field-1");
            retObj["requestname"] = fieldvalue;
        } else {
            var fieldvalue = WfForm.getFieldValue("field" + fieldid);
            retObj["field" + fieldid] = fieldvalue;
        }
    }
    retObj["requestname"] = WfForm.getFieldValue("field-1");
    return retObj;
}

export const cloneObject = (obj)=> {
    // Handle the 3 simple types, and null or undefined
    if (null == obj || "object" != typeof obj) return obj;

    // Handle Date
    if (obj instanceof Date) {
        var copy = new Date();
        copy.setTime(obj.getTime());
        return copy;
    }

    // Handle Array
    if (obj instanceof Array) {
        var copy = [];
        for (var i = 0; i < obj.length; i++) {
            copy[i] = cloneObject(obj[i]);
        }
        return copy;
    }

    // Handle Object
    if (obj instanceof Object) {
        var copy = {};
        for (var attr in obj) {
            if (obj.hasOwnProperty(attr)) copy[attr] = cloneObject(obj[attr]);
        }
        return copy;
    }

    throw new Error("Unable to copy obj! Its type isn't supported.");
}


export const ObjectEquals = (obj1, obj2)=> {
    if (obj1 == obj2)
        return true;
    if (typeof(obj2) == "undefined" || obj2 == null || typeof(obj2) != "object")
        return false;
    var length = 0;
    var length1 = 0;
    for (var ele in obj1) {
        length++;
    }
    for (var ele in obj2) {
        length1++;
    }
    if (length != length1)
        return false;
    if (obj2.constructor == obj1.constructor) {
        for (var ele in obj1) {
            if (typeof(obj1[ele]) == "object") {
                if (obj1[ele].constructor == Array) {
                    if (obj1[ele].toString() != obj2[ele].toString()) {
                        return false;
                    }
                } else if (!obj1[ele].equals(obj2[ele])) {
                    return false;
                } else if (typeof(obj1[ele]) == "function") {
                    if (obj1[ele].toString() != obj2[ele].toString()) {
                        return false;
                    }
                }
            } else if (obj1[ele] != obj2[ele]) {
                return false;
            }
        }
        return true;
    }
    return false;
}